/**
 * 
 */
package com.base.web.interceptor;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.base.annotation.LoginNeedless;
import com.base.util.LoginUtil;

/**
 * spring mvc 登陆拦截器
 * @author leiruiqi
 *
 */

public class BaseLoginInterceptor extends HandlerInterceptorAdapter {
	
	private String redirectUrl = "http://spring-domo-mvc/login.do";

	private final Logger logger = LoggerFactory.getLogger(BaseLoginInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		HandlerMethod handlerMethod=(HandlerMethod) handler;
		Class type = handlerMethod.getBeanType();
		Method method = handlerMethod.getMethod();
		//判断是否需有loginNeedless标记
		Annotation loginNeedless = type.getAnnotation(LoginNeedless.class);
		if(loginNeedless==null){
			loginNeedless = type.getSuperclass().getAnnotation(LoginNeedless.class);
		}
		if(loginNeedless==null){
			loginNeedless = handlerMethod.getMethodAnnotation(LoginNeedless.class);
			
		}
		
		if(loginNeedless!=null){
			return true;
		}
		
		
	
		if(!checkLogin(request,response)){
			response.sendRedirect(redirectUrl);
			return false;
		}
		
		return true;
		
	}
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		super.postHandle(request, response, handler, modelAndView);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		super.afterCompletion(request, response, handler, ex);
	}

	public String getRedirectUrl() {
		return redirectUrl;
	}

	public void setRedirectUrl(String redirectUrl) {
		this.redirectUrl = redirectUrl;
	}
	
	public boolean checkLogin(HttpServletRequest req, HttpServletResponse res){
		return LoginUtil.validateCookie(req,res,"a_b_c_d");
	}
}
